import React, { useState } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { Input } from 'antd';
import WebSvg from '@containers/asset-manage/components/asset-content/images/web.svg';
import _ from 'lodash';
import SelectWithCascader from '@components/select-with-cascader';
import FingerItem from '@components/finger-item';
import countryCodeMap from '@util/countryCodeMap';

const pingObj = {
  active: '有响应',
  unactive: '无响应'
};

const aggInfoArr = [
  { key: 'titles', name: '网站标题', className: 'site-title' },
  { key: 'wafs', name: '防护信息', className: 'waf' }
];

const infoArr = [
  { key: 'areaCode', name: '区域编码', className: 'areaCode' },
  { key: 'zipCode', name: '邮编', className: 'zipCode' },
  { key: 'timezone', name: '时区', className: 'timezone' }
];

const CMDBkey = [
  { key: 'uyunCMDB.cpu', name: 'cpu', className: 'cpu' },
  { key: 'uyunCMDB.mem', name: '内存', className: 'mem' },
  { key: 'uyunCMDB.disk', name: '磁盘', className: 'disk' },
  { key: 'uyunCMDB.vmState', name: '虚拟机状态', className: 'vmState' }
];

const renderLayer = (layer, title, currentDetail) => {
  if (layer === 'system') {
    const os = _.get(currentDetail, 'originOS', '') || _.get(currentDetail, 'os', '');
    const osId = _.get(currentDetail, 'os', '') || _.get(currentDetail, 'originOS', '');
    const isDomestic = (currentDetail.domesticList || []).some(_item => _item.name === osId);
    return (
      <div title={title} className={cn('layer', layer)}>
        <FingerItem name={os} key={os} fullName={os} rawType="os" isDomestic={isDomestic} />
      </div>
    );
  } else {
    const components = _.uniqBy(
      _.filter(_.flatten(_.map(currentDetail.portInfos, 'components')), {
        layer
      }),
      o => `${o.fullName || ''}_${o.rawType || ''}`
    );
    if (!components.length) {
      return false;
    }
    return (
      <div title={title} className={cn('layer', layer)}>
        {components.map(component => (
          <FingerItem {...component} key={component.fullName} />
        ))}
      </div>
    );
  }
};

function LeftContent(props) {
  const {
    currentDetail,
    onChangeSiteContent,
    onUpdateSite,
    ipError,
    urlError,
    nameError,
    emptyError,
    assetCategoryTree
  } = props;
  const [isAssetNameBlur, setIsAssetNameBlur] = useState(true);
  const pingableText = pingObj[currentDetail.pingable] || '未知';
  const { longitude, latitude, name, ip, url, country, continent, titles, ipv6 } = currentDetail;
  const assetName = name || (isAssetNameBlur && [].concat(titles).join(',')) || '';
  let location = [
    continent,
    country,
    _.get(currentDetail, 'region'),
    _.get(currentDetail, 'city'),
    _.get(currentDetail, 'county')
  ];
  location = location.includes('保留IP') ? '保留IP' : location.filter(Boolean).join('/');
  const countryMapElement =
    country && countryCodeMap[country] ? (
      <i className={`flag flag-${countryCodeMap[country]}`} />
    ) : null;

  const onAssetNameChange = e => {
    setIsAssetNameBlur(false);
    onChangeSiteContent('name', e.target.value);
  };

  const onAssetNameBlur = () => {
    setIsAssetNameBlur(true);
    onUpdateSite();
  };

  const checkRenderLayer = () => {
    const os = _.get(currentDetail, 'os');
    const components = _.uniqBy(
      _.flatten(_.map(currentDetail.portInfos, 'components')),
      o => `${o.fullName || ''}_${o.rawType || ''}`
    );
    if (!os && !components.length) {
      return false;
    }
    return true;
  };

  return (
    <div className="left">
      <div className={cn('info-item name', { error: nameError })}>
        <label>资产名称</label>
        <Input onChange={onAssetNameChange} value={assetName} onBlur={onAssetNameBlur} />
        {nameError && <div className="error-msg name-error">资产名称不能超过32个字符</div>}
      </div>

      <div className={cn('info-item url', { error: urlError })}>
        <label>URL</label>
        <Input
          onChange={e => onChangeSiteContent('url', e.target.value)}
          value={url}
          onBlur={onUpdateSite}
          addonAfter={
            <a href={url} target="_blank" rel="noopener noreferrer">
              <img src={WebSvg} alt="" />
            </a>
          }
        />
        {urlError && <div className="error-msg url-error">URL格式不正确</div>}
      </div>

      <div className={cn('info-item ip', { error: ipError || emptyError })}>
        <label>IP</label>
        <Input
          onChange={e => onChangeSiteContent(ipv6 ? 'ipv6' : 'ip', e.target.value)}
          value={ipv6 ? ipv6 : ip}
          onBlur={onUpdateSite}
        />

        {ipError && <div className="error-msg ip-error">IP格式不正确</div>}
        {emptyError && (
          <div className="error-msg empty-error">
            资产名称、URL、IP三个字段中需要至少有一个不为空{' '}
          </div>
        )}
      </div>
      {_.get(currentDetail, 'mac') && (
        <div className="info-item mac">
          <label>MAC地址</label>
          <span>{_.get(currentDetail, 'mac')}</span>
        </div>
      )}

      <div className="info-item category" style={{ position: 'static' }}>
        <label>资产分类</label>
        <SelectWithCascader
          mode="multiple"
          value={_.get(currentDetail, 'assetCategories', [])}
          options={assetCategoryTree}
          placeholder="请选择资产分类"
          fieldNames={{ label: 'name', value: '_id', children: 'children' }}
          onChange={categories => onChangeSiteContent('assetCategories', categories, onUpdateSite)}
        />
      </div>
      {aggInfoArr.map(item => {
        const { key, name, className } = item;
        return (
          _.get(currentDetail, `${key}.length`, 0) > 0 && (
            <div className={`info-item ${className}`} key={key}>
              <label>{name}</label>
              <span>{_.get(currentDetail, key, []).join(',') || '-'}</span>
            </div>
          )
        );
      })}
      <div className="info-item location">
        <label>地理位置</label>
        <div className="location-div">
          <span>
            {countryMapElement} {location || '-'}
          </span>
          <span>{longitude || latitude ? `(${longitude || '-'},${latitude || '-'})` : ''}</span>
        </div>
      </div>
      {infoArr.map(item => {
        const { key, name, className } = item;
        return (
          _.get(currentDetail, `${key}.length`, 0) > 0 && (
            <div className={`info-item ${className}`} key={key}>
              <label>{name}</label>
              <span>{_.get(currentDetail, key, '-') || '-'}</span>
            </div>
          )
        );
      })}
      {CMDBkey.map(item => {
        const { key, name, className } = item;
        return _.get(currentDetail, key) ? (
          <div className={`info-item ${className}`} key={key}>
            <label>{name}</label>
            <span>{_.get(currentDetail, key)}</span>
          </div>
        ) : null;
      })}

      <div className="info-item ping-status">
        <label>PING响应</label>
        <span className={cn('value', currentDetail.pingable)}>{pingableText || '-'}</span>
      </div>
      {checkRenderLayer() && (
        <div className="info-item finger">
          <label>指纹信息</label>
          <div className="finger-stack">
            {renderLayer('application', '应用层', currentDetail)}
            {renderLayer('support', '支撑层', currentDetail)}
            {renderLayer('service', '服务层', currentDetail)}
            {renderLayer('system', '系统层', currentDetail)}
          </div>
        </div>
      )}
    </div>
  );
}

LeftContent.propTypes = {
  currentDetail: PropTypes.object.isRequired,
  assetCategoryTree: PropTypes.object.isRequired,
  onChangeSiteContent: PropTypes.func.isRequired,
  onUpdateSite: PropTypes.func.isRequired,
  ipError: PropTypes.bool,
  urlError: PropTypes.bool,
  nameError: PropTypes.bool,
  emptyError: PropTypes.bool
};

LeftContent.defaultProps = {
  currentDetail: {},
  assetCategoryTree: {},
  onChangeSiteContent: () => {}
};

export default LeftContent;
